package wang.jinggo.cryptto;

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;

/**
 * 编写接收者的功能：使用发送者的公钥来验证发送过来的加密Data，判断签名的合法性
 * @author wangyj
 * @description
 * @create 2017-06-26 10:15
 **/
public class VerifySignature {

    public void run(){
        //这是GenerateKeyPair输出的公钥编码
        String pubkeyvalue = "30819f300d06092a864886f70d010101050003818d003081890281810085e6ff982b5a540003657a8b48f6375e0464efed024ecd2b79d8b605e2337bf8716b5b365e88682d0c814354e2a2fefdb9a5b16869deeb3e985341ecf6bb2adddfe9f0539ec8afea349eb3552f2ff81ac88772a316acac9bce0fb76b524cc64778d19375816409730e481d369e42a53763ac0d7ac50d7e0ef6939325b21db0750203010001";
        try {
            X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(hexStrToBytes(pubkeyvalue));
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PublicKey pubKey = keyFactory.generatePublic(bobPubKeySpec);

            String info = "orderId=10dkfadsfksdkssdkd&amount=80&orderTime=20060509";
            byte[] signed = hexStrToBytes("13346be429074d6eba97e3cc7a384d85b5424152c0b6cb055ada94f1d8018f154896b9634868747920cec7b7366bf9458ef8d74ed230f5da4295a2b28b25a2c6a16b18a6903cb1bb0187abaa40077a3702d75a0a7bd47eb7ba5d9d5a379b5425016fa761c5ef7b02ef1f1631c87824a1152fe8fe99f543ff3faee5e79db4c390");//这是SignatureData输出的数字签名
            Signature signetcheck = Signature.getInstance("MD5withRSA");
            signetcheck.initVerify(pubKey);
            signetcheck.update(info.getBytes());
            if (signetcheck.verify(signed)) {
                System.out.println("info=" + info);
                System.out.println("签名正常:" + bytesToHexStr(signed));
            }else {
                System.out.println("非签名正常");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Transform the specified byte into a Hex String form.
     */
    public static final String bytesToHexStr(byte[] bcd) {
        StringBuffer s = new StringBuffer(bcd.length * 2);

        for (int i = 0; i < bcd.length; i++) {
            s.append(bcdLookup[(bcd[i] >>> 4) & 0x0f]);
            s.append(bcdLookup[bcd[i] & 0x0f]);
        }

        return s.toString();
    }

    /**
     * Transform the specified Hex String into a byte array.
     */
    public static final byte[] hexStrToBytes(String s) {
        byte[] bytes;

        bytes = new byte[s.length() / 2];

        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) Integer.parseInt(s.substring(2 * i, 2 * i + 2),
                    16);
        }

        return bytes;
    }

    private static final char[] bcdLookup = { '0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
}
